package com.example.teamtribe.main.chat.friends;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.example.teamtribe.Application;
import com.example.teamtribe.R;
import com.example.teamtribe.UpdateService;
import com.example.teamtribe.base.BaseFragment;
import com.example.teamtribe.common.UsersAdapter;
import com.example.teamtribe.database.User;
import com.example.teamtribe.event.Friends;
import com.example.teamtribe.utils.Utility;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class FriendsFragment extends BaseFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private UsersAdapter adapter;
    private UpdateService.Binder binder;

    @Override
    protected int setContentView() {
        return R.layout.fragment_chat_friends;
    }

    @Override
    protected void onCreateView(View view) {
        binder = Application.getBinder();
        EventBus.getDefault().register(this);
        recyclerView = view.findViewById(R.id.rv_friends);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setNestedScrollingEnabled(false);
        adapter = new UsersAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                binder.getFriends();
            }
        });
    }

    @Override
    public void onResume() {
        initData();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Friends friends) {
        Log.d("接收事件", "好友列表");
        initData(friends.getFriends());
        refreshLayout.finishRefresh();
    }

    private void initData() {
        User user = Utility.getUser();
        initData(user.getFriends());
    }

    private void initData(List<Integer> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<User> users = new ArrayList<>(ids.size());
            for (int i : ids) {
                users.add(Utility.getT(i, User.class));
            }
            adapter.set(users);
            adapter.notifyDataSetChanged();
        }
    }
}
